<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blogs/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="golang,">





  <link rel="alternate" href="/blogs/atom.xml" title="恋恋风辰的个人博客" type="application/atom+xml">






<meta name="description" content="interface 意义？golang 为什么要创造interface这种机制呢？我个人认为最主要的就是做约束，定义一种规范，大家可以按照同一种规范实现各自的功能，从而实现多态。同时当interface做函数形参，可以很好地限制传入参数，并且根据不同的实参调用达到多态的效果。多态的意思就是多种多样的功能，比如我们定义了一个接口1234type IOInter interface&amp;#123;">
<meta name="keywords" content="golang">
<meta property="og:type" content="article">
<meta property="og:title" content="Go进阶篇(01) interface应用和复习">
<meta property="og:url" content="https://secondtonone1.gitee.io/blogs/2019/10/11/golang15/index.html">
<meta property="og:site_name" content="恋恋风辰的个人博客">
<meta property="og:description" content="interface 意义？golang 为什么要创造interface这种机制呢？我个人认为最主要的就是做约束，定义一种规范，大家可以按照同一种规范实现各自的功能，从而实现多态。同时当interface做函数形参，可以很好地限制传入参数，并且根据不同的实参调用达到多态的效果。多态的意思就是多种多样的功能，比如我们定义了一个接口1234type IOInter interface&amp;#123;">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://secondtonone1.gitee.io/blogs/2019/10/11/golang15/wxgzh.jpg">
<meta property="og:updated_time" content="2020-06-22T09:30:58.904Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Go进阶篇(01) interface应用和复习">
<meta name="twitter:description" content="interface 意义？golang 为什么要创造interface这种机制呢？我个人认为最主要的就是做约束，定义一种规范，大家可以按照同一种规范实现各自的功能，从而实现多态。同时当interface做函数形参，可以很好地限制传入参数，并且根据不同的实参调用达到多态的效果。多态的意思就是多种多样的功能，比如我们定义了一个接口1234type IOInter interface&amp;#123;">
<meta name="twitter:image" content="https://secondtonone1.gitee.io/blogs/2019/10/11/golang15/wxgzh.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blogs/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://secondtonone1.gitee.io/blogs/2019/10/11/golang15/">





  <title>Go进阶篇(01) interface应用和复习 | 恋恋风辰的个人博客</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">恋恋风辰的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blogs/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blogs/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://secondtonone1.gitee.io/blogs/blogs/2019/10/11/golang15/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="恋恋风辰">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogs/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="恋恋风辰的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Go进阶篇(01) interface应用和复习</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-10-11T15:10:37+08:00">
                2019-10-11
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/blogs/categories/golang/" itemprop="url" rel="index">
                    <span itemprop="name">golang</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="interface-意义？"><a href="#interface-意义？" class="headerlink" title="interface 意义？"></a>interface 意义？</h2><p>golang 为什么要创造interface这种机制呢？我个人认为最主要的就是做约束，定义一种规范，大家可以按照同一种规范实现各自的功能，从而实现多态。<br>同时当interface做函数形参，可以很好地限制传入参数，并且根据不同的实参调用达到多态的效果。多态的意思就是多种多样的功能，比如我们定义了一<br>个接口<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> IOInter <span class="keyword">interface</span>&#123;</span><br><span class="line">    write()<span class="keyword">int</span></span><br><span class="line">    read()<span class="keyword">int</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>定义了一个IOInter的接口，只要别人实现了write和read方法，都可以转化为这个接口。至于具体怎么读，读什么，网络IO还是文件IO取决于具体的实现，<br>这就形成了多样化的功能，从而实现多态。同时IOInter做函数的形参，<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">WriteFunc</span><span class="params">(io IOInter)</span></span>&#123;</span><br><span class="line">    io.Write()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<a id="more"></a>
<p>还达到了安全限制的功能。比如没有实现读写功能的类实例无法传给WriteFunc,WriteFunc内部调用io的Write函数会根据实参具体的实现完成特定的读写。<br>我们通过一个小例子实战下接口做形参的意义。golang中sort包提供了几个排序api，我们先实现一个int类型slice排序功能。<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">   arrayint := []<span class="keyword">int</span>&#123;<span class="number">6</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">5</span>, <span class="number">2</span>, <span class="number">7</span>&#125;</span><br><span class="line">sort.Ints(arrayint)</span><br><span class="line">fmt.Println(arrayint)</span><br></pre></td></tr></table></figure></p>
<p>sort.Ints可以完成对整形slice的排序，同样sort.Strings可以完成对string类型slice的排序<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">   arraystring := []<span class="keyword">string</span>&#123;<span class="string">"hello"</span>, <span class="string">"world"</span>, <span class="string">"Alis"</span>, <span class="string">"and"</span>, <span class="string">"Bob"</span>&#125;</span><br><span class="line">sort.Strings(arraystring)</span><br><span class="line">fmt.Println(arraystring)</span><br></pre></td></tr></table></figure></p>
<p>如果有这样一个需求，游戏中有很多个英雄，每个英雄有四个属性，攻击，防御，名字，出生时间，对这些英雄排序，从小到大，优先按照攻击排序，其次攻击相等的按<br>照防御排序，如果防御相等的按照出生时间排序。这是比较规则，我们根据sort包的Sort函数可以实现这个功能。<br>首先我们先定义英雄的结构<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Hero <span class="keyword">struct</span> &#123;</span><br><span class="line">	Name    <span class="keyword">string</span></span><br><span class="line">	Attack  <span class="keyword">int</span></span><br><span class="line">	Defence <span class="keyword">int</span></span><br><span class="line">	GenTime <span class="keyword">int64</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>其次我们再定义一个英雄列表<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> HeroList []*Hero</span><br></pre></td></tr></table></figure></p>
<p>接下来，我们看看golang的sort包实现的Sort源码<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">Sort</span><span class="params">(data Interface)</span></span> &#123;</span><br><span class="line">	n := data.Len()</span><br><span class="line">	quickSort(data, <span class="number">0</span>, n, maxDepth(n))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>可以看出，Sort函数有一个Interface类型的形参，我们继续查看Interface的类型<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Interface <span class="keyword">interface</span> &#123;</span><br><span class="line">	<span class="comment">// Len is the number of elements in the collection.</span></span><br><span class="line">	Len() <span class="keyword">int</span></span><br><span class="line">	<span class="comment">// Less reports whether the element with</span></span><br><span class="line">	<span class="comment">// index i should sort before the element with index j.</span></span><br><span class="line">	Less(i, j <span class="keyword">int</span>) <span class="keyword">bool</span></span><br><span class="line">	<span class="comment">// Swap swaps the elements with indexes i and j.</span></span><br><span class="line">	Swap(i, j <span class="keyword">int</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>可以看出Interface是一个接口，内部声明了三个方法Len,Less,Swap.<br>我们需要给自己的英雄列表实现这三个方法，就可以调用Sort排序了。先实现Len方法。<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(hl HeroList)</span> <span class="title">Len</span><span class="params">()</span> <span class="title">int</span></span> &#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">len</span>(hl)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Len功能很简单，就是实现了列表大小的获取。接下来实现比较函数Less,Less是按照我们之前说的英雄比较规则实现<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(hl HeroList)</span> <span class="title">Less</span><span class="params">(i, j <span class="keyword">int</span>)</span> <span class="title">bool</span></span> &#123;</span><br><span class="line">	<span class="keyword">if</span> i &lt; <span class="number">0</span> || j &lt; <span class="number">0</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	lenth := <span class="built_in">len</span>(hl)</span><br><span class="line">	<span class="keyword">if</span> i &gt;= lenth || j &gt;= lenth &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> hl[i].Attack != hl[j].Attack &#123;</span><br><span class="line">		<span class="keyword">return</span> hl[i].Attack &lt; hl[j].Attack</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> hl[i].Defence != hl[j].Defence &#123;</span><br><span class="line">		<span class="keyword">return</span> hl[i].Defence &lt; hl[j].Defence</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> hl[i].GenTime &lt; hl[j].GenTime</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>优先判断攻击是否相等，不相等就按照攻击力大小排序，小于返回true，从而实现从小到大排序<br>其次，攻击相等按照防御排序，以此类推。<br>接下来实现交换函数，交换英雄列表中的两个英雄<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(hl HeroList)</span> <span class="title">Swap</span><span class="params">(i, j <span class="keyword">int</span>)</span></span> &#123;</span><br><span class="line">	<span class="keyword">if</span> i &lt; <span class="number">0</span> || j &lt; <span class="number">0</span> &#123;</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	lenth := <span class="built_in">len</span>(hl)</span><br><span class="line">	<span class="keyword">if</span> i &gt;= lenth || j &gt;= lenth &#123;</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	hl[i], hl[j] = hl[j], hl[i]</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这样，我们的英雄列表功能和结构都设计好了，写个main函数测试下<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//自定义类型排序用sort.Sort</span></span><br><span class="line">	<span class="keyword">var</span> herolists HeroList</span><br><span class="line">	<span class="keyword">for</span> i := <span class="number">0</span>; i &lt; <span class="number">10</span>; i++ &#123;</span><br><span class="line">		generate := time.Now().Unix()</span><br><span class="line">		name := fmt.Sprintf(<span class="string">"Hero%d"</span>, generate)</span><br><span class="line">		hero := Hero&#123;</span><br><span class="line">			Name:    name,</span><br><span class="line">			Attack:  rand.Intn(<span class="number">100</span>),</span><br><span class="line">			Defence: rand.Intn(<span class="number">200</span>),</span><br><span class="line">			GenTime: generate,</span><br><span class="line">		&#125;</span><br><span class="line">		herolists = <span class="built_in">append</span>(herolists, &amp;hero)</span><br><span class="line">		time.Sleep(time.Duration(<span class="number">1</span>) * time.Second)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	sort.Sort(herolists)</span><br><span class="line">	<span class="keyword">for</span> _, value := <span class="keyword">range</span> herolists &#123;</span><br><span class="line">		fmt.Print(value.Name, <span class="string">" "</span>, value.Attack, <span class="string">" "</span>, value.Defence, <span class="string">" "</span>, value.GenTime, <span class="string">"\n"</span>)</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们通过for循环，每一秒生成一个英雄，攻击力和防御力随机，然后调用sort排序，接下来打印下看看效果<br><figure class="highlight cmd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Hero1570780749 <span class="number">11</span> <span class="number">45</span> <span class="number">1570780749</span></span><br><span class="line">Hero1570780744 <span class="number">25</span> <span class="number">140</span> <span class="number">1570780744</span></span><br><span class="line">Hero1570780748 <span class="number">28</span> <span class="number">74</span> <span class="number">1570780748</span></span><br><span class="line">Hero1570780750 <span class="number">37</span> <span class="number">106</span> <span class="number">1570780750</span></span><br><span class="line">Hero1570780742 <span class="number">47</span> <span class="number">59</span> <span class="number">1570780742</span></span><br><span class="line">Hero1570780745 <span class="number">56</span> <span class="number">100</span> <span class="number">1570780745</span></span><br><span class="line">Hero1570780747 <span class="number">62</span> <span class="number">89</span> <span class="number">1570780747</span></span><br><span class="line">Hero1570780741 <span class="number">81</span> <span class="number">87</span> <span class="number">1570780741</span></span><br><span class="line">Hero1570780743 <span class="number">81</span> <span class="number">118</span> <span class="number">1570780743</span></span><br><span class="line">Hero1570780746 <span class="number">94</span> <span class="number">111</span> <span class="number">1570780746</span></span><br></pre></td></tr></table></figure></p>
<p>看的出来，优先按照攻击力排序，攻击力相同则按照防御值排序。这样，这个排序的小功能就做好了。</p>
<h2 id="interface万能接口"><a href="#interface万能接口" class="headerlink" title="interface万能接口"></a>interface万能接口</h2><p>interface{}空接口可以接受任何类型的变量，从而可以实现类似于泛型编程的功能。golang本身并不支持泛型，原作者说泛型编程太过复杂，<br>以后会更新进来。<br>interface{}类型的变量在使用时要转化为具体的类型，否则会报错。转化方法前文提起过，现在复习一遍<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">   <span class="keyword">var</span> ife <span class="keyword">interface</span>&#123;&#125;</span><br><span class="line">ife = herolists</span><br><span class="line">val, ok := ife.(HeroList)</span><br><span class="line"><span class="keyword">if</span> !ok &#123;</span><br><span class="line">	fmt.Println(<span class="string">"ife can't transfer to HeroList!"</span>)</span><br><span class="line">	<span class="keyword">return</span></span><br><span class="line">&#125;</span><br><span class="line">fmt.Println(<span class="string">"herolist's len is "</span>, val.Len())</span><br></pre></td></tr></table></figure></p>
<p>herolists是上个例子定义的英雄列表，将它赋值给ife后，ife为interface{}类型,不能直接使用，所以用ife.(HeroList)来转换为HeroList<br>类型。<br>当然interface{}还可以做类型判断<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">JudgeType</span><span class="params">(itf <span class="keyword">interface</span>&#123;&#125;)</span></span> &#123;</span><br><span class="line">	<span class="keyword">switch</span> itf.(<span class="keyword">type</span>) &#123;</span><br><span class="line">	<span class="keyword">case</span> <span class="keyword">string</span>:</span><br><span class="line">		fmt.Println(<span class="string">"type is string"</span>)</span><br><span class="line">	<span class="keyword">case</span> <span class="keyword">int</span>:</span><br><span class="line">		fmt.Println(<span class="string">"type is int"</span>)</span><br><span class="line">	<span class="keyword">case</span> HeroList:</span><br><span class="line">		fmt.Println(<span class="string">"type is HeroList"</span>)</span><br><span class="line">	<span class="keyword">default</span>:</span><br><span class="line">		fmt.Println(<span class="string">"unknown type "</span>)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="interface实现万能类型双向链表"><a href="#interface实现万能类型双向链表" class="headerlink" title="interface实现万能类型双向链表"></a>interface实现万能类型双向链表</h2><p>基于上面的知识，我们再做一个例子，实现双向链表，支持头部插入，尾部插入，指定位置插入，指定位置删除，可存储任意类型数据<br>我们先定义链表的基本结构<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> LinkList <span class="keyword">struct</span> &#123;</span><br><span class="line">	Head *LinkEle</span><br><span class="line">	Tail *LinkEle</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> LinkEle <span class="keyword">struct</span> &#123;</span><br><span class="line">	Data <span class="keyword">interface</span>&#123;&#125;</span><br><span class="line">	Pre  *LinkEle</span><br><span class="line">	Next *LinkEle</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>LinkeEle是链表中的每个节点类型，包含Data数据域，其为interface{}类型，以及Pre指向前一个节点的指针，Next指向后一个节点的指针。<br>LinkList是链表结构，包含头和尾部节点的指针<br>好的，为了方便取出节点数据域，我们给LinkEle实现一个GetData方法。<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(le *LinkEle)</span> <span class="title">GetData</span><span class="params">()</span> <span class="title">interface</span></span>&#123;&#125; &#123;</span><br><span class="line">	<span class="keyword">return</span> le.Data</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>接下来我们实现插入操作，实现头部插入,基本思路为在头部节点前插入新节点，然后将新节点和头部节点连接，更新新节点为头部节点<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(ll *LinkList)</span> <span class="title">InsertHead</span><span class="params">(le *LinkEle)</span></span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> ll.Tail == <span class="literal">nil</span> &amp;&amp; ll.Head == <span class="literal">nil</span> &#123;</span><br><span class="line">		ll.Tail = le</span><br><span class="line">		ll.Head = ll.Tail</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	ll.Head.Pre = le</span><br><span class="line">	le.Pre = <span class="literal">nil</span></span><br><span class="line">	le.Next = ll.Head</span><br><span class="line">	ll.Head = le</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面先判断链表是否为空，如果链表为空，那么直接更新头尾信息即可，否则就需要执行连接操作。同样的道理我们实现尾部插入<br>尾部插入实在尾部节点的后边插入<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(ll *LinkList)</span> <span class="title">InsertTail</span><span class="params">(le *LinkEle)</span></span> &#123;</span><br><span class="line">	<span class="keyword">if</span> ll.Tail == <span class="literal">nil</span> &amp;&amp; ll.Head == <span class="literal">nil</span> &#123;</span><br><span class="line">		ll.Tail = le</span><br><span class="line">		ll.Head = ll.Tail</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	ll.Tail.Next = le</span><br><span class="line">	le.Pre = ll.Tail</span><br><span class="line">	le.Next = <span class="literal">nil</span></span><br><span class="line">	ll.Tail = le</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们测试下实现的功能<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">   ll := &amp;LinkList&#123;<span class="literal">nil</span>, <span class="literal">nil</span>&#125;</span><br><span class="line">fmt.Println(<span class="string">"insert head ....................."</span>)</span><br><span class="line"><span class="keyword">for</span> i := <span class="number">0</span>; i &lt; <span class="number">2</span>; i++ &#123;</span><br><span class="line">	num := rand.Intn(<span class="number">100</span>)</span><br><span class="line">	node1 := &amp;LinkEle&#123;Data: num, Next: <span class="literal">nil</span>, Pre: <span class="literal">nil</span>&#125;</span><br><span class="line">	ll.InsertHead(node1)</span><br><span class="line">	fmt.Println(num)</span><br><span class="line">&#125;</span><br><span class="line">fmt.Println(<span class="string">"after insert head ................."</span>)</span><br><span class="line"><span class="keyword">for</span> node := ll.Head; node != <span class="literal">nil</span>; node = node.Next &#123;</span><br><span class="line">	val, ok := node.GetData().(<span class="keyword">int</span>)</span><br><span class="line">	<span class="keyword">if</span> !ok &#123;</span><br><span class="line">		fmt.Println(<span class="string">"interface transfer error"</span>)</span><br><span class="line">		<span class="keyword">break</span></span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Println(val)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">fmt.Println(<span class="string">"insert tail ....................."</span>)</span><br><span class="line"><span class="keyword">for</span> i := <span class="number">0</span>; i &lt; <span class="number">2</span>; i++ &#123;</span><br><span class="line">	num := rand.Intn(<span class="number">100</span>)</span><br><span class="line">	node1 := &amp;LinkEle&#123;Data: num, Next: <span class="literal">nil</span>, Pre: <span class="literal">nil</span>&#125;</span><br><span class="line">	ll.InsertTail(node1)</span><br><span class="line">	fmt.Println(num)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">fmt.Println(<span class="string">"after insert tail ................."</span>)</span><br><span class="line"><span class="keyword">for</span> node := ll.Head; node != <span class="literal">nil</span>; node = node.Next &#123;</span><br><span class="line">	val, ok := node.GetData().(<span class="keyword">int</span>)</span><br><span class="line">	<span class="keyword">if</span> !ok &#123;</span><br><span class="line">		fmt.Println(<span class="string">"interface transfer error"</span>)</span><br><span class="line">		<span class="keyword">break</span></span><br><span class="line">	&#125;</span><br><span class="line">	fmt.Println(val)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>我们初始化了一个LinkList类型的链表变量ll,然后在头部插入两个节点，在尾部插入两个节点,看看效果<br><figure class="highlight cmd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">insert head .....................</span><br><span class="line"><span class="number">81</span></span><br><span class="line"><span class="number">87</span></span><br><span class="line">after insert head .................</span><br><span class="line"><span class="number">87</span></span><br><span class="line"><span class="number">81</span></span><br><span class="line">insert tail .....................</span><br><span class="line"><span class="number">47</span></span><br><span class="line"><span class="number">59</span></span><br><span class="line">after insert tail .................</span><br><span class="line"><span class="number">87</span></span><br><span class="line"><span class="number">81</span></span><br><span class="line"><span class="number">47</span></span><br><span class="line"><span class="number">59</span></span><br></pre></td></tr></table></figure></p>
<p>头部插入先插入81,然后插入87，所以列表变为87,81<br>接着尾部插入47,59，列表变为87,81,47,59<br>接下来实现在指定位置的节点后插入节点<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(ll *LinkList)</span> <span class="title">InsertIndex</span><span class="params">(le *LinkEle, index <span class="keyword">int</span>)</span></span> &#123;</span><br><span class="line">	<span class="keyword">if</span> index &lt; <span class="number">0</span> &#123;</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> ll.Head == <span class="literal">nil</span> &#123;</span><br><span class="line">		ll.Head = le</span><br><span class="line">		ll.Tail = ll.Head</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	node := ll.Head</span><br><span class="line">	indexfind := <span class="number">0</span></span><br><span class="line">	<span class="keyword">for</span> ; indexfind &lt; index; indexfind++ &#123;</span><br><span class="line">		<span class="keyword">if</span> node.Next == <span class="literal">nil</span> &#123;</span><br><span class="line">			<span class="keyword">break</span></span><br><span class="line">		&#125;</span><br><span class="line">		node = node.Next</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> indexfind != index &#123;</span><br><span class="line">		fmt.Println(<span class="string">"index is out of range"</span>)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//node 后边的节点缓存起来</span></span><br><span class="line">	nextnode := node.Next</span><br><span class="line"></span><br><span class="line">	<span class="comment">//node 和le连接起来</span></span><br><span class="line">	node.Next = le</span><br><span class="line">	le.Pre = node</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> node == ll.Tail &#123;</span><br><span class="line">		ll.Tail = le</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//le和next node 连接起来</span></span><br><span class="line">	<span class="keyword">if</span> nextnode != <span class="literal">nil</span> &#123;</span><br><span class="line">		nextnode.Pre = le</span><br><span class="line">		le.Next = nextnode</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>首先判断链表是否为空，如果为空，则直接更新节点为列表头尾节点。否则判断插入位置是否越界，如果越界则直接返回。<br>如果不越界，则将节点插入，并判断插入节点是否为最后位置，如果为最后位置，则更新其为尾结点。<br>接下来我们测试在第三个节点后边插入节点。补充代码如下，前边的插入不变，看下效果<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">fmt.Println(<span class="string">"insert after third element........"</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		num := rand.Intn(<span class="number">100</span>)</span><br><span class="line">		node1 := &amp;LinkEle&#123;Data: num, Next: <span class="literal">nil</span>, Pre: <span class="literal">nil</span>&#125;</span><br><span class="line">		ll.InsertIndex(node1, <span class="number">2</span>)</span><br><span class="line">		fmt.Println(num)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	fmt.Println(<span class="string">"after insert index ................."</span>)</span><br><span class="line">	<span class="keyword">for</span> node := ll.Head; node != <span class="literal">nil</span>; node = node.Next &#123;</span><br><span class="line">		val, ok := node.GetData().(<span class="keyword">int</span>)</span><br><span class="line">		<span class="keyword">if</span> !ok &#123;</span><br><span class="line">			fmt.Println(<span class="string">"interface transfer error"</span>)</span><br><span class="line">			<span class="keyword">break</span></span><br><span class="line">		&#125;</span><br><span class="line">		fmt.Println(val)</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure></p>
<p>结果如下<br><figure class="highlight cmd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">insert head .....................</span><br><span class="line"><span class="number">81</span></span><br><span class="line"><span class="number">87</span></span><br><span class="line">after insert head .................</span><br><span class="line"><span class="number">87</span></span><br><span class="line"><span class="number">81</span></span><br><span class="line">insert tail .....................</span><br><span class="line"><span class="number">47</span></span><br><span class="line"><span class="number">59</span></span><br><span class="line">after insert tail .................</span><br><span class="line"><span class="number">87</span></span><br><span class="line"><span class="number">81</span></span><br><span class="line"><span class="number">47</span></span><br><span class="line"><span class="number">59</span></span><br><span class="line">insert after third element........</span><br><span class="line"><span class="number">81</span></span><br><span class="line">after insert index .................</span><br><span class="line"><span class="number">87</span></span><br><span class="line"><span class="number">81</span></span><br><span class="line"><span class="number">47</span></span><br><span class="line"><span class="number">81</span></span><br><span class="line"><span class="number">59</span></span><br></pre></td></tr></table></figure></p>
<p>前边是头部和尾部插入的输出，接着我们在第三个位置节点后插入81,打印看到确实插入在了47的后边。<br>同样我们接下来实现删除操作，删除指定位置的节点<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(ll *LinkList)</span> <span class="title">DelIndex</span><span class="params">(index <span class="keyword">int</span>)</span></span> &#123;</span><br><span class="line">	<span class="keyword">if</span> index &lt; <span class="number">0</span> &#123;</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> ll.Head == <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	node := ll.Head</span><br><span class="line">	indexfind := <span class="number">0</span></span><br><span class="line">	<span class="keyword">for</span> ; indexfind &lt; index; indexfind++ &#123;</span><br><span class="line">		<span class="keyword">if</span> node.Next == <span class="literal">nil</span> &#123;</span><br><span class="line">			<span class="keyword">break</span></span><br><span class="line">		&#125;</span><br><span class="line">		node = node.Next</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> indexfind != index &#123;</span><br><span class="line">		fmt.Println(<span class="string">"index is out of range"</span>)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> ll.Head == ll.Tail &#123;</span><br><span class="line">		ll.Tail = <span class="literal">nil</span></span><br><span class="line">		ll.Head = ll.Tail</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//如果是头节点</span></span><br><span class="line">	<span class="keyword">if</span> node == ll.Head &#123;</span><br><span class="line">		ll.Head = node.Next</span><br><span class="line">		node.Next.Pre = <span class="literal">nil</span></span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//如果是尾结点</span></span><br><span class="line">	<span class="keyword">if</span> node == ll.Tail &#123;</span><br><span class="line">		ll.Tail = node.Pre</span><br><span class="line">		ll.Tail.Next = <span class="literal">nil</span></span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//将前后连接起来</span></span><br><span class="line">	node.Pre.Next = node.Next</span><br><span class="line">	node.Next.Pre = node.Pre</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>和插入操作类似，判断是否为空链表，是否只有一个节点等情况，接着判断删除的是否为头结点，是否为尾节点，否则就执行删除后的连接操作。<br>继续上边的测试代码，我们添加如下测试代码补充测试<br><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">fmt.Println(<span class="string">"delete second element, its index is 1"</span>)</span><br><span class="line">	ll.DelIndex(<span class="number">1</span>)</span><br><span class="line">	fmt.Println(<span class="string">"after delete second element, its index is 1"</span>)</span><br><span class="line">	<span class="keyword">for</span> node := ll.Head; node != <span class="literal">nil</span>; node = node.Next &#123;</span><br><span class="line">		val, ok := node.GetData().(<span class="keyword">int</span>)</span><br><span class="line">		<span class="keyword">if</span> !ok &#123;</span><br><span class="line">			fmt.Println(<span class="string">"interface transfer error"</span>)</span><br><span class="line">			<span class="keyword">break</span></span><br><span class="line">		&#125;</span><br><span class="line">		fmt.Println(val)</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure></p>
<p>输出如下<br><figure class="highlight cmd"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">87</span></span><br><span class="line"><span class="number">81</span></span><br><span class="line"><span class="number">47</span></span><br><span class="line"><span class="number">81</span></span><br><span class="line"><span class="number">59</span></span><br><span class="line">delete second element, its index is <span class="number">1</span></span><br><span class="line">after delete second element, its index is <span class="number">1</span></span><br><span class="line"><span class="number">87</span></span><br><span class="line"><span class="number">47</span></span><br><span class="line"><span class="number">81</span></span><br><span class="line"><span class="number">59</span></span><br></pre></td></tr></table></figure></p>
<p>我们删除了index为1，也就是第二个节点81，测试成功了。<br>由于链表的数据域Data为空接口类型，所以可以存储各种类型的数据，只需要在GetData时做具体类型转换即可。<br>接下来读者可以自己考虑实现删除头部节点，删除尾部节点等。<br>可以下载我的源码 :<br><a href="https://github.com/secondtonone1/golang-/tree/master/day26" target="_blank" rel="noopener">https://github.com/secondtonone1/golang-/tree/master/day26</a></p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>本文通过两个小例子实战，演示了interface常用的用法，为接下来讲解反射做铺垫。<br>感谢关注我的公众号<br><img src="wxgzh.jpg" alt="wxgzh.jpg"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/golang/" rel="tag"># golang</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2019/09/24/golang14/" rel="next" title="golang 接口内部实现">
                <i class="fa fa-chevron-left"></i> golang 接口内部实现
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2019/10/14/golang16/" rel="prev" title="Go进阶篇(02) 反射用法详解">
                Go进阶篇(02) 反射用法详解 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">恋恋风辰</p>
              <p class="site-description motion-element" itemprop="description">重剑无锋，大巧不工</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives/">
              
                  <span class="site-state-item-count">146</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blogs/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blogs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/secondtonone1" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/wang-wu-chen-32/activities" target="_blank" title="ZhiHu">
                    
                      <i class="fa fa-fw fa-ZhiHu"></i>ZhiHu</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#interface-意义？"><span class="nav-number">1.</span> <span class="nav-text">interface 意义？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#interface万能接口"><span class="nav-number">2.</span> <span class="nav-text">interface万能接口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#interface实现万能类型双向链表"><span class="nav-number">3.</span> <span class="nav-text">interface实现万能类型双向链表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">恋恋风辰</span>

  
  
 
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
 
 
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.3</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blogs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
